import React, {useEffect, useState} from "react";
import {Button, Dropdown, Input, MenuProps, Popconfirm, Select, Table} from "antd";
import PojApi from "@/api/PojApi.ts";
import {IPage, ObjInfo, PojInfoDto} from "@/api/Types/ObjInterfaces.ts";
import UserInfoViewer from "@/components/UserInfoViewer.tsx";
import SavePojModal from "@/pages/ContextPage/AdminPage/AdminPojPage/SavePojModal.tsx";
import {Link} from "react-router-dom";
import ObjApi from "@/api/ObjApi.ts";
import AddObjToPojModal from "@/components/AddObjToPojModal.tsx";

const AdminPojPage: React.FC = () => {
    // 创建/修改项目窗口
    const [savePojModalOpen, setSavePojModalOpen] = useState(false)
    // 页面刷新
    const [r, setR] = useState(0)
    const refresh = () => {
        setR(r + 1)
    }
    // 分页项目信息数据
    const [pojInfoPage, setPojInfoPage] = useState<IPage<PojInfoDto>>(null)
    // 查询的项目类型
    const [selectPojType, setSelectPojType] = useState<string>(null)
    // 用户信心预览
    const [userInfoViewer, setUserInfoViewer] = useState<UserInfoViewer>()
    const [pojTypes, setPojTypes] = useState<string[]>([])
    const [addObjModal, setAddObjModal] = useState(false)
    const [selectPojId, setSelectPojId] = useState<string>(null)

    useEffect(() => {
        PojApi.pagePoj(1, 10, selectPojType).then(data => {
            UserInfoViewer.init(data.records.map(item => item.createUser)).then(viewer => {
                setPojInfoPage(data)
                setUserInfoViewer(viewer)
            })
        })
        PojApi.getPojTypes().then((data) => {
            setPojTypes(data)
        })
    }, [r]);

    const DataTable: React.FC = () => {
        return (
            <Table
                dataSource={pojInfoPage.records}
                pagination={{
                    current: pojInfoPage.current,
                    total: pojInfoPage.total,
                    onChange: (page, pageSize) => {
                        PojApi.pagePoj(page, pageSize, selectPojType).then(data => {
                            UserInfoViewer.init(data.records.map(item => item.createUser)).then(viewer => {
                                setPojInfoPage(data)
                                setUserInfoViewer(viewer)
                            })
                        })
                    },
                    showSizeChanger: true,
                }}
                rowKey="id"
            >
                <Table.Column title="项目id"
                              dataIndex="id"
                />
                <Table.Column title="名称"
                              dataIndex="name"
                              render={(value: string, record: PojInfoDto, index) => {
                                  return (
                                      <Input
                                          defaultValue={value}
                                          variant="filled"
                                          onBlur={(evt) => {
                                              const newVal = evt.target.value;
                                              if (newVal == value) {
                                                  return
                                              }
                                              PojApi.savePojInfo({
                                                  description: null,
                                                  id: record.id,
                                                  pojType: null,
                                                  refObjList: null,
                                                  name: newVal
                                              }).then((res) => {
                                                  window.messageApi.success("更新成功：项目id：" + res.data).then()
                                              })
                                          }}
                                      />
                                  )
                              }}
                />
                <Table.Column title="介绍"
                              dataIndex="description"
                              render={(value: string, record: PojInfoDto, index) => {
                                  return (
                                      <Input
                                          defaultValue={value}
                                          variant="filled"
                                          onBlur={(evt) => {
                                              const newVal = evt.target.value;
                                              if (newVal == value) {
                                                  return
                                              }
                                              PojApi.savePojInfo({
                                                  description: newVal,
                                                  id: record.id,
                                                  pojType: null,
                                                  refObjList: null,
                                                  name: null,
                                              }).then((res) => {
                                                  window.messageApi.success("更新成功：项目id：" + res.data).then()
                                              })
                                          }}
                                      />
                                  )
                              }}
                />
                <Table.Column title="类型"
                              dataIndex="pojType"
                                render={(value, record: PojInfoDto, index) => {
                                    return (
                                        <Select
                                            options={pojTypes.map(item => ({
                                                name: item,
                                                value: item
                                            }))}
                                            defaultValue={value}
                                            onChange={(newVal) => {
                                                if (value == newVal) {
                                                    return
                                                }
                                                PojApi.savePojInfo({
                                                    description: null,
                                                    id: record.id,
                                                    pojType: newVal,
                                                    refObjList: null,
                                                    name: null,
                                                }).then((res) => {
                                                    window.messageApi.success("更新成功：项目id：" + res.data).then()
                                                })
                                            }}
                                        />
                                    )
                                }}
                />
                <Table.Column title="引用的对象"
                              dataIndex="objInfoList"
                              render={(value: ObjInfo[], record: PojInfoDto) => {
                                  // TODO 设计下拉菜单来添加和删除引用
                                  if (value == null || value.length == 0) {
                                        return (
                                            <div>空</div>
                                        )
                                  }
                                  return (
                                      value.map(item => {
                                          return (
                                              <Button
                                                  key={'对象' + item.id}
                                                  type='link'
                                                  onClick={() => {
                                                      console.log(ObjApi.getObjLink(item.objLink))
                                                      // todo 完成对象的预览
                                                  }}
                                              >
                                                  {item.objName}
                                              </Button>
                                          )
                                      })
                                  )
                              }}
                />
                <Table.Column title="创建时间"
                              dataIndex="createTime"
                              render={(value: string, record) => {
                                  const date = new Date(value)
                                  // TODO 设计一个钟
                                  return date.toString()
                              }}
                />
                <Table.Column title="更新时间"
                              dataIndex="updateTime"
                />
                <Table.Column title="归属用户"
                              dataIndex="createUser"
                              render={(value, record, index) => {
                                  return (
                                      <Button
                                          onClick={() => {
                                              userInfoViewer.show(value)
                                          }}
                                          type='text'
                                      >
                                          {userInfoViewer.getNickNameById(value)}
                                      </Button>
                                  )
                              }}
                />
                <Table.Column title="操作"
                              dataIndex="id"
                              render={(value, record: PojInfoDto, index) => {
                                  return (
                                      <>
                                          <Button
                                              onClick={() => {
                                                  setAddObjModal(true)
                                                  setSelectPojId(value)
                                              }}
                                              type='link'
                                          >添加对象</Button>
                                          <Popconfirm title="确认删除"
                                                      onConfirm={() => {
                                                          PojApi.deletePoj(value).then((value) => {
                                                              window.messageApi.success('删除成功').then()
                                                              refresh()
                                                          })
                                                      }}
                                          >
                                              <Button
                                                  type='text'
                                              >
                                                  删除项目
                                              </Button>
                                          </Popconfirm>
                                      </>
                                  )
                              }}
                />
            </Table>
        )
    }


    return (
        <div>
            <Button onClick={() => {
                setSavePojModalOpen(true)
            }}>
                创建项目
            </Button>
            {pojInfoPage == null ? <Table/> : <DataTable/>}
            <SavePojModal
                open={savePojModalOpen}
                setOpen={(flag: boolean) => {
                    setSavePojModalOpen(flag)
                    refresh()
                }}
            />
            <AddObjToPojModal
                open={addObjModal}
                setOpen={(flag: boolean) => {
                    setAddObjModal(flag)
                    refresh()
                }}
                pojId={selectPojId}
            />
        </div>
    )
}

export default AdminPojPage